package com.zkadmin.controller;

import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import com.zkadmin.constraints.RolelConstraint;
import com.zkadmin.entity.SysRole;
import com.zkadmin.service.SysRoleService;
import com.zkadmin.util.AdminConstants;

@SuppressWarnings("serial")
public class CreateRoleDialogCtrl extends BaseCtrl<Window> {

	@WireVariable
	private SysRoleService sysRoleService;

	@Wire
	private Window win;

	@Wire
	private Textbox name;
	@Wire
	private Textbox role;

	@Override
	protected void init(Window win) {
		this.win = win;
		role.setConstraint(new RolelConstraint());
	}

	@Listen("onClick=#cancelBtn")
	public void closeDialog(Event e) {
		win.onClose();
	}

	@Listen("onClick=#okBtn")
	public void createRole(Event e) {
		if (sysRoleService.findByName(role.getValue()) != null) {
			throw new WrongValueException(role, "【" + role.getValue() + "】角色已经存在。");
		}
		if (sysRoleService.findByName(name.getValue()) != null) {
			throw new WrongValueException(name, "【" + name.getValue() + "】角色名称已经存在。");
		}

		SysRole newRole = new SysRole();
		newRole.setName(name.getValue());
		newRole.setRole(role.getValue());
		sysRoleService.save(newRole);
		Events.postEvent(AdminConstants.EVENT_ONREFRESH, win, null);
		win.onClose();
	}

}
